function hostReg(){
    return reg.test($("#url").val()) ?true:false
}
function DeBug(){
    ShowMsg("")
    let url    = $("#url").val()
    let model  = $("#debugModel option:selected").val()
    if(!hostReg() && $.inArray(url,rightModels) != -1){
        layer.msg("请检查页面网址是否正确,http或者https一定得带哦！");
        return
    }
    if($.inArray(model,yaliModels) != -1){
        if(!hostReg()){
            layer.msg("请检查页面网址是否正确,http或者https一定得带哦！")
            return 
        }
        apiSend("PressureTest")
    }else if($("#debugModel option:selected").val() == "CHEST"){
        let chest = $("input[name='chest']:checked").val()
        if (chest == "IPTOCITY"){
            ipToCity()
        }else if(chest == "STRSEARCH"){
            strSeach(0)
        }else if(chest == "DIRSEARCH"){
            strSeach(1)
        }else if(chest == "TIMETODATE"){
            timeToDate()
        }
    }else if($("#debugModel option:selected").val() == "REGXP"){
        regXp()
    }else{
        clearInterval(setIntervalId);
        x = parseInt($("#Second").val());
        XId = 0;
        DaoJiShi();
    }
}

//修改placeholder
function changePlaceholder(){
    let model = $("#debugModel option:selected").val()
    let msg = ""
    if ($.inArray(model, urlModels) != -1) {
        msg = "大神，网址记得带上http或者https哦"
    }else if(model == "REGXP"){
        msg = "大神，填写正则的时候前后不要带//哦！"
    }else if(model == "CHEST"){
        msg = "请根据下面的单选按钮输入正确的内容！"
    }
    if(modelsUrlValues[model]){
        $("#url").val(modelsUrlValues[model])
    }else{
        $("#url").val("")
    }
    $("#url").attr("placeholder",msg);
}

function url(){
    if($("#debugModel option:selected").val() == "REGXP"){
        regXp();
    }
}

function GetDir(InitNum){
    $(".serachP").show("slow")
    $("#url").attr("placeholder","大神，这里你可以输入你想要搜索的字符串！");
    
    let dirReg = /\/?/
    if((dirReg.test($(".nowPath").html()) && CurrentDir.length < 1 && InitNum == 0) || (InitNum == 1 && dirReg.test($(".nowPath").html()))){
        //获取系统目录
        let Data = {};
        Data.type = "GetPathInfo";
        Data.data = "disk";
        ws.send(json(Data))   
    }
}
//改变百宝箱的模式 serachP
function changeChest(InitNum){
    if($.inArray($("input[name=chest]:checked").val(),fileSystemModels2) != -1  || $.inArray($("#debugModel option:selected").val(),fileSystemModels) != -1){
        GetDir(InitNum)
    }else{
        $(".chestBox .serachP").hide("slow")
    }
}

function setApiResponsModel(){
    let m = $("#ApiResponsModel option:selected").val()
    if(apiBodyBox != null){
        ApiResponsModel = m
        apiBodyBox.getSession().setMode("ace/mode/" + ApiResponsModel);
    }
}
//切换模式
function changeModel(){
    //清除文档信息，防止页面卡顿
    $("#regStr").val("")
    $(".apiBody pre").html("")
    $(".performance").css("display","none")

    changePlaceholder() //修改输入框的提示信息
    let model = $("#debugModel option:selected").val()
    let show  = ''
    let hide  = ''
    if($.inArray(model, rightModels) != -1){
        $("#code").val("")
        $(".fileDir").html("")
        $(".codeBox,.lockPageDisplaySpan,.debugModel2").hide("slow")
        closeiframeHeightSet() //先关闭修改高度
        stop();
        $(".apiBody,#apiBodyPre").show("slow")
        $("#iframe,#apiBodyBox").hide("slow");
    //     $(".apiBody").html('<pre></pre>')
    //    $(".apiBody").removeClass("ace_editor")
    //    $(".apiBody").removeClass("ace-monokai")
    //    $(".apiBody").removeClass("ace_dark")
        if($.inArray($("#debugModel option:selected").val(),yaliModels) == -1){
            $(".params").hide("slow")
            hide += ",.params"
            if($("#debugModel option:selected").val() == "REGXP"){
                pageGet();//防止火狐等浏览器缓存 记录不显示
                $(".regText").show("slow")
                $(".chestBox").hide("slow")
            }else{
                changeChest(0);
                $(".regText").hide("slow")
                $(".chestBox").show("slow")
            }
        }else{
            $(".bingfa-params,.params").show("slow")
            $(".regText,.chestBox").hide("slow")
        }
        $(".YALISHOW").hide("slow");
        $("#OpenMysql").attr("data-status","no")
        OpenMysql()
        // $(".box").animate({
        //     left:"50%",
        //     width:"50%",
        //     height:"100%",
        //     bottom:"-30px",
        // },800)
        $(".box").addClass("boxRigthModel")
        $("#OpenMysql").hide("slow");
    }else{
        $("#DeBug").css("pointer-events","auto")
        $(".bingfa-params").hide("slow")
        $(".regText,#apiBodyPre").hide("slow")
        $(".lockPageDisplaySpan,.debugModel2,#apiBodyBox").show("slow")
        if($("#debugModel option:selected").val() == "NORMAL"){
            $(".iframeHeightSetP").show("slow");
            $("#iframe").show("slow"); 
           $(".apiBody").hide("slow")
        }else{
            $(".iframeHeightSetP").hide("slow");
            $("#iframe").hide("slow");
            $(".apiBody").show("slow")
        }

        $(".YALISHOW").show("slow");
        $("#OpenMysql").show("slow");
        $(".chestBox").hide("slow")
        $(".params").show("slow");
        $(".box").removeClass("boxRigthModel")
       // let h =  $("#params-form p").length < 14 ? (172 + 43 * (parseInt($("#params-form p").length - 1) / 2)) + "px" :(172 + 43 * 6) + "px"
        // $(".box").animate({
        //     left:"0px",
        //     width:"100%",
        //     bottom:"0px",
        //   //  height:h
        // },800)
        $("#OpenMysql").attr("data-status","yes")
        if(ChangeChanelCount == 0){
             //OpenMysql()
        }
        iframeWidthSet();
        lockPageDisplay();
    }   
    if($("#isOpen").val() == "yes"){
        DeBug()
    }
    ShowMsg(""); //清空提示
    ChangeChanelCount++
}


function lockPageDisplay(){
    if($("#lockPageDisplay").prop("checked")){
        $(".setHetBox").show("slow");
        iframeWidthSet();
        setIframeHeight();
        GetDir(0)
    }else{
        closeiframeHeightSet()
    }
}
//停止刷新
function stop(){
    $("#isOpen").val("no")
    clearInterval(setIntervalId);
    $("#ShowMsg").html("");
}

function DaoJiShi(){
    let model  = $("#debugModel option:selected").val()
    let model2 = $("#debugModel2 option:selected").val()

    let s = new Date().valueOf();
    $("#isOpen").val("yes")
    let url = $("#url").val();
    let iframe = id("iframe");
    let Second = parseInt($("#Second").val());
    if(!hostReg()){
        ShowMsg("请检查页面网址是否正确,http或者https一定得带哦！");
        return
    }	
    if(model2 == 'AUTO'){
        if(x <= 0){
            x = Second;
            $("#ShowMsg").html("刷新中......请稍等");
            clearInterval(setIntervalId);
            reGet();
        }else{
            if(x == Second && XId == 0){//第一次点击进来
                reGet();
                XId++;
            }
            $("#ShowMsg").html("还有<i>" + x + "</i>秒将刷新！");
            x--;
    
        }
    }else{
        clearInterval(setIntervalId);    
        $("#ShowMsg").html("");
        reGet();
    }
}


//刷新
function reGet(){
    let m = $("#debugModel option:selected").val();
    let model2 = $("#debugModel2 option:selected").val()
    let url = $("#url").val();
    let iframe = id("iframe");
   
    if(m != "NORMAL"){
        $(".apiBody").css("display","block");
        apiSend("api");
    }else{
        let Data = {};
        Data.type = "NORMAL";
        Data.data = url;
        ws.send(json(Data)) 

        $(".apiBody").css("display","none");
        let urlReg = /\?/g
        if(urlReg.test(url)){
            url += "&t="
        }else{
            url += "?t="
        }
        url += "t=" + Math.random()
        startTime  =  new Date().getTime()
        //解决vue.js angulat react等前端框架带#url问题导致load监听失效问题
        if((/\/#/).test($("#url").val())){
            window.localStorage.setItem(startTime,"no")
            let url2 = "http://" + window.location.host + "/show?url=" + window.btoa(url) + "&token=" + startTime
            let getIframeLoadTimeI      = 0
            let getIframeLoadTimeId     = setInterval(()=>{
                getIframeLoadTimeI++
                if(getIframeLoadTimeI >= 600){
                    clearInterval(getIframeLoadTimeId) //300秒还没响应就踢出不再统计
                    window.localStorage.removeItem(startTime)//清除缓存垃圾
                }else{
                    if(window.localStorage.getItem(startTime) != "no"){
                        //同步缓存 画走势图
                        if (showPerformance){
                            createNormalPageModelMap(window.sessionStorage.getItem(startTime))
                        }
                        clearInterval(getIframeLoadTimeId) //300秒还没响应就踢出不再统计
                        window.localStorage.removeItem(startTime)//清除缓存垃圾
                    }
                }
            },500)
            $("#show").attr("src",url2)
        }
        iframe.setAttribute("src",url);  
    }
    if(model2 == 'AUTO'){
        setIntervalId = setInterval("DaoJiShi()",1000); 
    }
}
//api请求
function apiSend(type){

    Data = {};
    Data.type = type;
    Data.model = $("#debugModel option:selected").val();
    Data.url = $("#url").val();


   let params = ""
   let headerParams = ""
   let cookieParams = ""
   let paramsIndex = 0
   let headerParamsIndex = 0
   let cookieParamsIndex = 0
    $("#params-form p").each(function(i){

        k = $("#params-form p").eq(i).find(".key").val();
        v = $("#params-form p").eq(i).find(".value").val();
        let normalReg = /normal/g
        let headerReg = /header/g
        //获取选中的类别
        let checkName = $(this).find("input").eq(0).attr("name") 
        let keyValueType = $(this).find("input[name='" + checkName + "']:checked").val()
        if(k != ""){
            let  keyValueStr = k + "=" + v
            if(normalReg.test(keyValueType)){
                if(paramsIndex > 0) {
                    params += "&" + keyValueStr
                }else{
                    params += keyValueStr
                    paramsIndex++
                }
            }else if(headerReg.test(keyValueType)){
                if(headerParamsIndex > 0) {
                    headerParams += "&" + keyValueStr
                }else{
                    headerParams += keyValueStr
                    headerParamsIndex++
                }
            }else{
                if(cookieParamsIndex > 0) {
                    cookieParams += "&" + keyValueStr
                }else{
                    cookieParams += keyValueStr
                    cookieParamsIndex++
                }
            }
        }     
    })
    
    if(type == "PressureTest"){
        if ($(".C").val().length  < 1 || $(".N").val().length < 1){
            ShowMsg("并发数或者链接数为空");
            return
        }else if(parseInt($(".C").val()) > parseInt($(".N").val())){
            ShowMsg("并发数不能大于链接数");
            return
        }else{
            Data.C = $(".C").val()
            Data.N = $(".N").val()
            ShowMsg("")
            Data.agreement = "no"
            if($("input[name='agreement']:checked").val()){
                Data.agreement = $("input[name='agreement']:checked").val();
            }
            $("#DeBug").css("pointer-events","none"); //防止重复点击
            $(".apiBody pre").html("<div class='jindu'></div><div class='JieGuo' >进度：<progress value='0' max='100.00'></progress> <span class='progress-span'>0</span>%</div>");
        }

    }

    Data.data = params
    Data.headerParams = headerParams
    Data.cookieParams = cookieParams
    Data = json(Data)
    //发送数据到服务器
    ws.send(Data)
}
function OpenMysql(){
    if($("#OpenMysql").attr("data-status") == "yes"){
        if(ChangeChanelCount !=0){
            closeMysql("yes")
        }
        if($.inArray($("#debugModel option:selected").val(),rightModels) != -1){
           // ShowMsg("抱歉，侧栏模式暂时不打开监控哦！")
            return 
        }
        $("#Mysqlbox").show("slow")
        $("#OpenMysql").html("隐藏mysql监控");
        $("#OpenMysql").attr("data-status","no");
    }else{
        if(ChangeChanelCount !=0){
            closeMysql("no")
        }
        $("#OpenMysql").html("打开mysql监控");
        $("#Mysqlbox").hide("slow")     
        $("#OpenMysql").attr("data-status","yes");
    }
}
//关闭后台数据库监控
function closeMysql(status){
    if(ws){
        let Data = {};
        Data.type = "CLOSEMYSQL";
        Data.status = status;
        ws.send(json(Data))
    }
}
function hidenDebug(){
//    changeModel()
    $(".box").hide("slow");
    $(".openDebug").show("slow");
    $("#OpenMysql").attr("data-status","no")
    OpenMysql()
}
function openDebug(){
    //changeModel()
    $(".openDebug").hide("slow");
    $(".box").show("slow");
    $("#OpenMysql").attr("data-status","yes")
    OpenMysql()
}
function id(id){
    return document.getElementById(id);
}
//删除参数
function delParam(obj){
    $(obj).parent().remove()
    //changeBoxHeight();
}
//添加参数
function addParam(){
    let keyValueType = "keyValueType" + Math.random()
    let str = `<p><span class="params-span params-span-active" onclick="setParamsChecked(this)"><input name="`+keyValueType+`" type="radio" value="normal" checked  />普通参数 </span><span class="params-span" onclick="setParamsChecked(this)"><input name="`+keyValueType+`" type="radio" value="header"   /> Header参数</span><span class="params-span" onclick="setParamsChecked(this)"><input name="`+keyValueType+`" type="radio" value="cookie"   />Cookie参数  </span>&nbsp;&nbsp;&nbsp;&nbsp;Key：<input type='text' class='key' class="keyValue"/>Value：<input type='text' class='value' class="keyValue" /><button onclick=delParam(this)>删除</button> </p>`
    $("#params-form").append(str)
    //changeBoxHeight();
    let model = $("#debugModel option:selected").val()
    if($.inArray(model,fileSystemModels) != -1 && $("#OpenMysql").attr("data-status") == "no"){
        OpenMysql()
    }

    let h = 35
    let n = $(".params-list p").length  
    h = $.inArray(model,fileSystemModels) != -1 ? Math.ceil(n / 2) * h : h * n;
    $(".params-list").scrollTop(h)
    //addParamGoMoreModel();
}

//
function addParamGoMoreModel(){
    let model = $("#debugModel option:selected").val()
    if($.inArray(model,rightModels) != -1){
        $(".params-list").removeClass("paramsMoreMode")
    }else{
        if($(".params-list p").length > 1 && !$(".params-list").hasClass("paramsMoreMode")){
            $(".params-list").addClass("paramsMoreMode")
        }
    }
}

//修改box高度
function changeBoxHeight(){
    if($("#debugModel option:selected").val() != "YALI-GET" && $("#debugModel option:selected").val() != "YALI-POST"){
        if($("#params-form p").length < 14){
            var h = 172 + 45 * (parseInt($("#params-form p").length - 1) / 2); 
            $(".box").animate({
                height: h + "px",
            },800)   
        }
    }
}
//查看全部
function readAll(){
    $(".apiBody pre .jindu").animate({
        top:"0px",
    },1000)
    $(".readAll").remove(); //删除该元素
}

//编辑器制造对应行数
function createLingNumbers(){
    let regexp = new RegExp("\n", "g");
    res = $("#code").val().match(regexp)
    if(!res || res.length == null){
        return
    }
    let c = res.length
    //ChangeRows()
    if (c > 100){   
        $("#code").attr("row",c);   
    }
    let h = (c * 20) + 100 + "px"
    $(".codeMain").css("height",h);
    $("#code").css("height",(c * 20) + "px");
    //开始制造行数
    str = ""
    for(let i = 1; i <= c; i++){
        str += "<p>" + i + "</p>"
    }
    $(".codeLline").html(str) //清空行数
}
//初始化iframe的宽高
window.onload = function(){

    var iframe = id("iframe");
    PageWidth  = window.screen.width
    PageHeight = window.screen.height
    iframe.style.width = window.screen.width+"px";
    iframe.style.height = window.screen.height+"px";
    $("#iframeWidthSet").val(parseInt(window.screen.width));
    $("#iframeWidthSet").attr("max",parseInt(window.screen.width));
    $("#debugModel").find("option[value='NORMAL']").attr("selected", "selected");
    $(".codeBox").animate({
        display:"block",
        width: parseInt(PageWidth) / 2 + "px",
    },800);
    $(".codeMain").css({
        width: (parseInt(PageWidth) / 2 ) + "px",
    })
    //初始化编程语言
    let ops = ""
    for(let i = 0; i < Langs.length; i++){
        ops += '<option value="' + Langs[i][1] + '">' + Langs[i][0] + '</option>'
    }
    $("#SetLang").html(ops) 
    ChangeCodeBoxWidth()
    //验证宽度
    if(PageWidth < 1920){
        layer.msg("您的分辨率过低，系统不建议使用，请使用1920*1080或更高的分辨率体验！")
    }
    //增加拖曳组件
   Drag()



   //获取缓存
   perFormance =  window.localStorage.getItem("perFormance") ? JSON.parse(window.localStorage.getItem("perFormance")) :perFormance
   //监听网页模式加载渲染时间
   $("#iframe").load(function(){   
        $("#debugModel option:selected").val() == 'NORMAL' && !(/\/#/).test($("#url").val())  ? createNormalPageModelMap((new Date().getTime() - startTime)) : ''
   });   

   //检查是否设置用户名
   if (window.localStorage.getItem("User") == undefined){
        showSetUserInfo()
   }
   //检查是否设置用户名
   if (window.localStorage.getItem("netImgHistory") != undefined){
    netImgHistory = JSON.parse(window.localStorage.getItem("netImgHistory"))
    }
    if (window.localStorage.getItem("editHistoryList") != undefined){
        editHistoryList = JSON.parse(window.localStorage.getItem("editHistoryList"))
    }
   getHistory();
   //contactList[0].Msg = msgLists //同步历史消息过去
   UpdateContactList(1)
   UserList(QLList)
   
   addParam()
   addParam()

   $('#url').bind('keypress',function(event){
    if(event.keyCode == "13") {
        DeBug()
    }
    if($("#debugModel option:selected").val() == "REGXP"){
        regXp();
    }
    });
   $('#msg').bind('keypress',function(event){
    if(event.keyCode == "13") {
        sendMsg()
    }
    });

   //检查是否有历史消息记录
   if (window.localStorage.getItem("msgLists") != undefined){
        msgLists = JSON.parse(window.localStorage.getItem("msgLists"))
        // for(let i = 0;i < msgLists.length; i++){
        //     WriteMsg(msgLists[i])
        // }
       // $(".sendBox").click()
    }
    hsitoryHasShow = true
};

function createNormalPageModelMap(time){
    time = parseInt(time)
    let haoshi = time > 1000 ? (time / 1000).toFixed(2) + 's' : time + 'ms'
    let model = $("#debugModel option:selected").val()
    let url = window.btoa($("#url").val())

    if(!perFormance[model][url]){
        perFormance[model][url]  = {
            now:haoshi,
            avg:haoshi,
            max:haoshi,
            min:haoshi,
            timeList:[time],
            dateList:[getTime()]
        }
    }else{
        perFormance[model][url].timeList.push(time)
        perFormance[model][url].dateList.push(getTime())
        perFormance[model][url].now= haoshi
        let timeSum = 0
        let avg  = 0
        let max  = getTimeNum(perFormance[model][url].max)
        let min  = getTimeNum(perFormance[model][url].min)
        let timeCount = perFormance[model][url].timeList.length
        for(let i = 0; i < timeCount; i++ ){
            timeSum += perFormance[model][url].timeList[i]
        }
        avg = (timeSum/timeCount).toFixed(2)
        perFormance[model][url].avg = numToTime(avg)

        perFormance[model][url].max = time > max[0] ? haoshi : numToTime(max[0])
        perFormance[model][url].min = time < min[0] ? haoshi : numToTime(min[0])

    }
    //画图
    createMap(perFormance[model][url].dateList,perFormance[model][url].timeList)
   //更新缓存
   window.localStorage.setItem("perFormance",JSON.stringify(perFormance))

   hasPerformance = true
   if (showPerformance){
    $(".performance").css("display","inline-block")
    }
    let innerHTML = "网页加载渲染性能调试(" + perFormance[model][url].timeList.length + ")次记录报表【可拖动】"
    innerHTML    += "<hr/>&nbsp;&nbsp;地址：<span class='performance-url'>" +  $("#url").val()
    innerHTML    += "</span><br/>&nbsp;&nbsp;最新：" +  haoshi
    innerHTML    += "<br/>&nbsp;&nbsp;最慢：" +  perFormance[model][url].max 
    innerHTML    += "<br/>&nbsp;&nbsp;最快：" +  perFormance[model][url].min 
    innerHTML    += "<br/>&nbsp;&nbsp;平均：" +  perFormance[model][url].avg
    innerHTML    += `<br/>&nbsp;&nbsp;<button onclick="clearPerformanceLog('${model}','${url}')" style="font-size:14px;font-weight:normal;padding:5px;cursor:pointer">清空记录</button><span style='color:#ccc;font-size:12px;font-weight:normal;'> 记录如果过多，请及时清理，不然可能会影响浏览器性能！</span>`
    innerHTML    += `<div class='showNewNumber'>耗时：${haoshi}<hr/>性能：${checkPagePerFormance(time)}</div>`
    $(".performance-haoshi").html(innerHTML)
}
function json(obj){
    return JSON.stringify(obj);
}
function echo($) {
    console.log($);
}
function ShowMsg(str) {
    $("#ShowMsg").html("<i>" + str + "</i>");
    $(".apiBody pre").html("<h1>" + str + "</h1>");
}

$(function(){
    changeModel()
});